"use strict";
var utils = {
	_loadedRes: {},
	PATH_TEMP: "#",
	path: function(pathName) {
		return utils.PATH_TEMP.replace("#", pathName);
	},
	loadScript:function(url, callback){
		var scriptElem = document.createElement('script');
		scriptElem.onload = callback;
		scriptElem.src = url;
		document.body.appendChild(scriptElem);
	},
	loadJson: function(url, callback) {
		$.ajax({ url: url, success: function(data) {
			data = (typeof data === "string")? JSON.parse(data) : data;
			callback(data);
		} });
	},
	getRes: function(name) {
		var r = utils._loadedRes[name];
		if (!r) console.warn("not find:"+ name);
		return r;
	},
	loadRes: function(arr, callback) {
		arr = arr.forEach?arr:[arr];
		var loadNum = arr.length;
		arr.forEach(function(src) {
			if (utils._loadedRes[src.name]) return onload(); 
			switch(src.type) {
				case "image":
					var img = new Image();
        			if (!src.noAnonymous) img.crossOrigin = "Anonymous";
					img.onload = onload;
					img.src = src.url;
					utils._loadedRes[src.name] = img;
					break;
				case "js":
					utils.loadScript(src.url, onload);
					break;
				case "json":
					utils.loadJson(src.url, function(data) {
						utils._loadedRes[src.name] = data;
						onload();
					});
					break;
			}

		});

		function onload(){
			loadNum --;
			if (loadNum === 0) {
				callback && callback();
			}
		}
	},

	loadAtals: function(spritePath, callback) {
		var loadNum = 2;
		var bitmapObj = {};

		var img = new Image();
		var spriteData;
		img.onload = onload;
		img.src = spritePath + ".png";
		bitmapObj.img = img;

		utils.loadJson(spritePath + ".json", function(data) {
			spriteData = data;
			onload();
		});

		function onload() {
			loadNum--;
			if(loadNum===0) {
				callback && callback(img, spriteData);
			}
		}

	},

	loadSkeleton: function(skeletonPath, name, callback){
		var self = this;
		var loadNum = 3;
		var img, textureData, skeletonData;
		utils.loadRes([
			{ url: self.path(skeletonPath+"_tex.png"),  type: "image", name: name+"_tex_png" },
			{ url: self.path(skeletonPath+"_tex.json"), type: "json", name: name+"_tex_json" },
			{ url: self.path(skeletonPath+"_ske.json"), type: "json", name: name+"_ske_json" }
		], function() {
			img = utils.getRes(name+"_tex_png");
			textureData = utils.getRes(name+"_tex_json");
			skeletonData = utils.getRes(name+"_ske_json");
			callback && callback(img, textureData, skeletonData);
		});

	},

	getUrlKey:function(){
		var that = this;
		if(this.keys) {
			return this.keys;
		}

		var search = location.search.slice(1);
		this.keys = {};
		if(search){
			var arr = search.split('&');
			arr.forEach(function(kv){
				var kvs = kv.split('=');
				if(kvs.length === 2){
					that.keys[kvs[0]] = kvs[1];
				}
			});
		}
		this.keys.type = this.keys.type||'dom';
		this.keys.anim = this.keys.anim||'dragon';

		return this.keys;
	},

	setUrlKey: function() {
		var search = '?';
		for(var k in this.keys){
			search += k + '=' + this.keys[k] + '&';
		}
		location.search = search.slice(0, -1);
	},

	randomNum: function(max, min) {
		min = min || 0;
		return min + Math.round( Math.random() * (max - min) );
	},
	
	getCharLength: function(str) {
		var str_length = 0;
		var str_len = 0;
		str_len = str.length;
		for (var i = 0; i < str_len; i++) {
			var a = str.charAt(i);
			str_length++;
			if (escape(a).length > 4) {
				str_length++;
			}
		}
		return str_length;
	},

	sliceStr: function(str, len) {
		var rs = [];
		var strLen = str.length;
		var curMeasureLen = 0;
		var curChars = "";
		for (var i = 0; i < strLen; i++) {
			var a = str.charAt(i);
			var alen = 1;
			if (escape(a).length > 4) { alen++; }
			if (curMeasureLen>=len) {
				rs.push(curChars);
				curChars = a;
				curMeasureLen = alen;
			} else {
				curMeasureLen += alen;
				curChars += a;
			}
		}
		rs.push(curChars);
		return rs;
	},

	dataURLtoBlob: function(dataurl) {
	    var arr = dataurl.split(','),
	        mime = arr[0].match(/:(.*?);/)[1],
	        bstr = atob(arr[1]),
	        n = bstr.length,
	        u8arr = new Uint8Array(n);
	    while (n--) {
	        u8arr[n] = bstr.charCodeAt(n);
	    }
	    return new Blob([u8arr], { type: mime });
	},

	getObjectURL: function(file) {
	    var url = null;
	    if (window.createObjectURL !== undefined) { // basic
	        url = window.createObjectURL(file);
	    } else if (window.URL !== undefined) { // mozilla(firefox)
	        url = window.URL.createObjectURL(file);
	    } else if (window.webkitURL !== undefined) { // webkit or chrome
	        url = window.webkitURL.createObjectURL(file);
	    }
	    return url;
	}

};

(function() {
	var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    var ua = window.navigator.userAgent.toLowerCase();
    var isWx = ua.match(/MicroMessenger/i) == 'micromessenger';
	utils.isAndroid = isAndroid;
	utils.isiOS = isiOS;
	utils.isWx = isWx;
}());